﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts;
using DataContexts.Supplier;

public partial class Admin_User_Default : System.Web.UI.Page
{
    private UserDataContext userCntx = new UserDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.AdminUserDefault;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!IsPostBack)
        {
            gvUser.DataSource = from u in userCntx.Users
                                join ut in userCntx.UserTypes on u.UserType equals ut.UserTypeId
                                select new { u.UserId, u.Username, u.EmailAddress, UserType = ut.UserTypeName, Active = (u.Active.Value ? "Yes" : "No") };
            gvUser.DataBind();
        }
    }
    protected void gvUser_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvUser.DataKeys[e.RowIndex].Value);
        if (HasSupplier(id))
        {
            divError.InnerHtml = "User cannot be deleted because user is associated to supplier. <br/><br/>";
            return;
        }
        else
        {
            var user = userCntx.Users.SingleOrDefault(u => u.UserId == id);
            userCntx.Users.DeleteOnSubmit(user);
            userCntx.SubmitChanges();
            Response.Redirect("default.aspx");
        }
    }

    private bool HasSupplier(int id)
    {
        SupplierDataContext suppCntx = new SupplierDataContext();
        List<Supplier> supp = (from u in suppCntx.Suppliers
                   where u.UserId == id
                   select u).ToList<Supplier>();

        return supp.Count > 0;
    }
    protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((LinkButton)e.Row.Cells[5].Controls[0]).OnClientClick = "return confirm(\"Are you sure you want to delete '" + e.Row.Cells[0].Text + "' user?\");";
        }
    }
}
